package com.itheima.sfbx.insurance.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.sfbx.framework.commons.exception.ProjectException;
import com.itheima.sfbx.framework.commons.utils.BeanConv;
import com.itheima.sfbx.insurance.dto.CoefficentVO;
import com.itheima.sfbx.insurance.enums.CoefficentEnum;
import com.itheima.sfbx.insurance.mapper.CoefficentMapper;
import com.itheima.sfbx.insurance.pojo.CategoryCoefficent;
import com.itheima.sfbx.insurance.pojo.Coefficent;
import com.itheima.sfbx.insurance.pojo.InsuranceCoefficent;
import com.itheima.sfbx.insurance.service.ICategoryCoefficentService;
import com.itheima.sfbx.insurance.service.ICoefficentService;
import com.itheima.sfbx.insurance.service.IInsuranceCoefficentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description：系数项服务实现类
 */
@Slf4j
@Service
public class CoefficentServiceImpl extends ServiceImpl<CoefficentMapper, Coefficent> implements ICoefficentService {

    @Autowired
    private ICategoryCoefficentService categoryCoefficentService;

    @Autowired
    private IInsuranceCoefficentService insuranceCoefficentService;

    private LambdaQueryWrapper<Coefficent> queryWrapper(CoefficentVO coefficentVO){
        LambdaQueryWrapper<Coefficent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(coefficentVO.getCoefficentKey()),Coefficent::getCoefficentKey,coefficentVO.getCoefficentKey())
                .like(StrUtil.isNotBlank(coefficentVO.getCoefficentKeyName()),Coefficent::getCoefficentKeyName,coefficentVO.getCoefficentKeyName())
                .eq(StrUtil.isNotBlank(coefficentVO.getDataState()),Coefficent::getDataState,coefficentVO.getDataState());
        return queryWrapper;
    }

    //系数项分页查询
    @Override
    public Page<CoefficentVO> findPage(CoefficentVO coefficentVO, int pageNum, int pageSize) {
        Page<Coefficent> page = this.page(new Page<>(pageNum, pageSize), queryWrapper(coefficentVO));
        return BeanConv.toPage(page,CoefficentVO.class);
    }

    @Override
    public CoefficentVO findById(String coefficentId) {
        //根据id查询
        Coefficent coefficent = this.getById(coefficentId);
        if(coefficent==null){
            log.error("不存在该系数项数据");
            throw new ProjectException(CoefficentEnum.FIND_ONE_FAIL);
        }
        return BeanConv.toBean(coefficent,CoefficentVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CoefficentVO save(CoefficentVO coefficentVO) {
        //新增系数项
        //健壮性判断，key要唯一
        Integer count = this.lambdaQuery()
                .eq(Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .count();
        if(count>0){
            log.error("系数项key已经存在，key为：{}",coefficentVO.getCoefficentKey());
            throw new ProjectException(CoefficentEnum.SAVE_FAIL);
        }
        Coefficent coefficent = BeanConv.toBean(coefficentVO, Coefficent.class);
        this.save(coefficent);
        return BeanConv.toBean(coefficent,CoefficentVO.class);
    }

    @Override
    @Transactional
    public Boolean update(CoefficentVO coefficentVO) {
        //编辑
        //健壮性判断，判断是否存在该系数项
        Coefficent coefficent = this.getById(coefficentVO.getId());
        if(coefficent==null){
            log.error("不存在该系数项数据,id为：{}",coefficentVO.getId());
            throw new ProjectException(CoefficentEnum.SAVE_FAIL);
        }
        //判断修改后的key是否唯一,这算一个筛选条件
        Integer count = this.lambdaQuery()
                .eq(Coefficent::getCoefficentKey, coefficentVO.getCoefficentKey())
                .ne(Coefficent::getId, coefficentVO.getId())
                .count();
        if (count > 0) {
            log.error("筛选项的key已存在，key为：{}", coefficentVO.getCoefficentKey());
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }
        //判断是否有冗余字段，即是否被其他的表引用，相同数据存在在多个表中
        Integer count1 = categoryCoefficentService.lambdaQuery()
                .eq(CategoryCoefficent::getCoefficentKey, coefficent.getCoefficentKey())
                .count();
        Integer count2 = insuranceCoefficentService.lambdaQuery()
                .eq(InsuranceCoefficent::getCoefficentKey, coefficent.getCoefficentKey())
                .count();
        if (count1 > 0 || count2 > 0) {
            log.error("保障项被关联，不能修改，key为：{}",coefficent.getCoefficentKey());
            throw new ProjectException(CoefficentEnum.UPDATE_FAIL);
        }
        Coefficent coefficent1 = BeanConv.toBean(coefficentVO, Coefficent.class);
        return this.updateById(coefficent1);
    }

    @Override
    @Transactional
    public Boolean delete(String[] checkedIds) {
        //删除系数项
        List<String> ids = Arrays.asList(checkedIds);
        //先把保障项查出来
        List<Coefficent> coefficents = this.listByIds(ids);
        if (CollUtil.isEmpty(coefficents)) {
            log.info("保障项不存在，ids：{}", ids);
            return true;
        }
        Set<String> keys = coefficents.stream().map(Coefficent::getCoefficentKey).collect(Collectors.toSet());
        Integer count1 = categoryCoefficentService.lambdaQuery()
                .in(CategoryCoefficent::getCoefficentKey, keys)
                .count();
        Integer count2 = insuranceCoefficentService.lambdaQuery()
                .in(InsuranceCoefficent::getCoefficentKey, keys)
                .count();
        if (count1 > 0 || count2 > 0) {
            log.error("存在系数项被关联，不能删除，keys为：{}", keys);
            throw new ProjectException(CoefficentEnum.DEL_FAIL);
        }
        return this.removeByIds(ids);
    }

    @Override
    public List<CoefficentVO> findList(CoefficentVO coefficentVO) {
        //查询系数项列表集合
        List<Coefficent> list = this.list(queryWrapper(coefficentVO));
        if(CollUtil.isEmpty(list)){
            log.error("没有系数项数据,请求参数为:{}",coefficentVO);
            throw new ProjectException(CoefficentEnum.LIST_FAIL);
        }
        return BeanConv.toBeanList(list,CoefficentVO.class);
    }

    @Override
    public CoefficentVO findByCoefficentKey(String coefficentKey) {
        //根据key查询系数项数据
        Coefficent coefficent = this.lambdaQuery().eq(Coefficent::getCoefficentKey, coefficentKey).one();
        if(coefficent==null){
            log.error("不存在系数项key为{}的数据",coefficentKey);
            throw new ProjectException(CoefficentEnum.FIND_ONE_FAIL);
        }
        return BeanConv.toBean(coefficent,CoefficentVO.class);
    }
}
